import numpy as np
import cv2
import os


def B2M(source,destination):

    if os.path.isfile(destination):
        print("%s has been existed!" % (destination))
        return
    size = get_FileSize(source)
    if size > 100 :
        print("%s is to long !!!" % (destination))
        return
    if size == 0 :
        print("%s is zero !!!" % (destination))
        return

    f = open(source, mode='rb')
    image = np.fromfile(f, dtype=np.ubyte)

    filesize = image.shape[0]

    width = 256 #设置图片宽度为256
    rem = filesize%width
    if rem != 0:
        image = image[:-rem]
    height = int(image.shape[0]/width)

    image = image.reshape(height,width)

    if not os.path.isfile(source):
        print("%s not exist!" % (source))
    else:
        print("b2m %s -> %s" % (source,destination))
        fpath, fname = os.path.split(destination)  # 分离文件名和路径
        if not os.path.exists(fpath):
            os.makedirs(fpath)  # 创建路径
        # cv2.imwrite(destination, image)
        cv2.imencode('.png', image)[1].tofile(destination)
        cv2.waitKey(0)

def get_FileSize(filePath):
    filePath = filePath.encode('utf8')
    fsize = os.path.getsize(filePath)
    fsize = fsize/float(1024*1024)
    return round(fsize,2)


#B2M('.\\Download\\095a3df95d2145e431fe1af5fa964996-Clever_Internet_ActiveX_Suite_v6.2.exe','.\\你好\\095a3df95d2145e431fe1af5fa964996-Clever_Internet_ActiveX_Suite_v6.2.png')